package com.gurid.service.sms.controller;

import com.aliyuncs.exceptions.ClientException;
import com.gurid.common.base.result.R;
import com.gurid.common.base.result.ResultCode;
import com.gurid.common.base.util.FormUtils;
import com.gurid.common.base.util.RandomUtils;
import com.gurid.service.base.exception.GuridException;
import com.gurid.service.sms.service.SmsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/sms")
@Tag(name = "ApiSmsController", description = "阿里云短信服务")
//@CrossOrigin
@Slf4j
public class ApiSmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Operation(description = "获取验证码")
    @GetMapping("send/{mobile}")
    public R getCode(@Parameter(description = "手机号", required = true) @PathVariable String mobile) throws ClientException {

        //校验手机号
        if (!(StringUtils.hasText(mobile)
                && mobile.length() == 11
                && FormUtils.isMobile(mobile))) {
            log.error("手机号不正确");
            throw new GuridException(ResultCode.LOGIN_PHONE_ERROR);
        }
        //生成验证码
        String checkCode = RandomUtils.getSixBitRandom();
        System.out.println(checkCode);
        //发送验证码
        //smsService.send(mobile, checkCode);
        //存储验证码到redis，有效期5分钟
        redisTemplate.opsForValue().set(mobile, checkCode, 5, TimeUnit.MINUTES);

        return R.ok().message("短信发送成功");
    }
}
